import {UIButton, UIInput, UIPanel, UIRow, UIText} from "../../js/threejs/libs/ui.js";

export default class DeviceDetailFunction {

  constructor(displayer) {
    let scope = this
    let request = displayer.request

    let container = new UIPanel()
    container.dom.style.padding = '20px'
    container.dom.style.overflowY = 'auto'
    container.dom.style.height = `${displayer.VIEWPORT_HEIGHT - 35 - 40}px`
    container.dom.style.color = '#00fcff'

    this.container = container

    let functionPanel
    let updateUI = (functions) => {

      // 1、先删除
      if (functionPanel !== undefined) {
        container.remove(functionPanel)
      }
      // 2、再动态添加
      functionPanel = this.buildFunctionStru(functions || []);
      container.add(functionPanel)
    }

    displayer.signals.deviceDetailed.add(object => {
      request.getAction('/display/getInstanceFunction', {instanceId: object.uuid}).then((res) => {
        if (res.success) {
          updateUI(res.result)
        }
      })
    })
  }

  buildFunctionStru(functions) {
    console.log(functions)
    let functionPanel = new UIPanel()
    console.log(document.getElementById('function'))
    if(functions === undefined || functions.length <= 0) {
      document.getElementById('function').style.display = 'none'
      return functionPanel;
    } else {
      document.getElementById('function').style.display = 'inline-block'
    }
    for (const func of functions) {
      console.log(func)
      // 自动执行的功能，不加载
      if (func.type === 'auto') {
        continue
      }
      let funcPanel = new UIPanel()
      funcPanel.setClass('function-panel')
      funcPanel.dom.style.borderTop = '1px #0ffcff solid'
      funcPanel.dom.style.padding = '10px'
      funcPanel.dom.style.display = 'flex'
      funcPanel.dom.style.alignItems = 'center'
      let funcButton = new UIButton(func.name)
      funcButton.setClass('funcButton')
      funcButton.onClick(() => this.invokeFunction(func))
      funcPanel.add(funcButton)
      let paramsPanel = new UIPanel()
      funcPanel.add(paramsPanel)
      func['inputParams']
        .filter(inputParam => inputParam.inputMode.indexOf("opt_input") !== -1)
        .map(extendParam => {
          let extendParamRow = new UIRow()
          let value = new UIInput(extendParam.value)
          value.setClass('funcParam')
          extendParamRow.add(new UIText(extendParam.name + '：'))
          extendParamRow.add(value)
          paramsPanel.add(extendParamRow)
        })
      functionPanel.add(funcPanel)
    }
    return functionPanel
  }

  invokeFunction(func) {
    // 删除功能输入参数中的metadata元素
    func.inputParams.map(input => {
      delete input.metadata
    })
    console.log("执行功能 >>>>> ", func)
    displayer.request.postAction('/device/instance/invokeFunction', func).then((res) => {
      if (res.success) {
        console.log(res.message)
      }
    })
  }
}